import 'package:casdon/core/utils/permission/PermissionService.dart';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

import 'package:permission_handler/permission_handler.dart';

enum PermissionViewState { granted, denied, permanentlyDenied }

// 继承 FamilyNotifier
class PermissionNotifier
    extends FamilyNotifier<PermissionViewState, AppPermission> {
  @override
  PermissionViewState build(AppPermission permission) {
    // 初始化默认状态为 denied
    _checkPermission(permission);
    return PermissionViewState.denied;
  }

  Future<void> _checkPermission(AppPermission permission) async {
    final status = await PermissionService.check(permission);
    if (status.isGranted) {
      state = PermissionViewState.granted;
    } else if (status.isPermanentlyDenied) {
      state = PermissionViewState.permanentlyDenied;
    } else {
      state = PermissionViewState.denied;
    }
  }

  Future<void> requestPermission(AppPermission permission) async {
    final status = await PermissionService.request(permission);
    if (status.isGranted) {
      state = PermissionViewState.granted;
    } else if (status.isPermanentlyDenied) {
      state = PermissionViewState.permanentlyDenied;
    } else {
      state = PermissionViewState.denied;
    }
  }

  Future<void> refresh(AppPermission permission) async {
    await _checkPermission(permission);
  }
}

// FamilyNotifierProvider
final permissionProvider =
    NotifierProvider.family<
      PermissionNotifier,
      PermissionViewState,
      AppPermission
    >(() => PermissionNotifier());
